package mac_tools;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.text.Normalizer;
import java.util.List;
/*
 *  OSX��Java�̊֌W�͈ȉ��̂Ƃ���B
�o�[�W����	�@�@�@�@�@�@�@�@�@�@�@�@�@�@J2SE1.4	J2SE5	Java SE 6
Mac OS X 10.3 (Panther)	�@�@�@�@��	�@�@�@�@�@�~	�@�@�@�~
Mac OS X 10.4 (Tiger)	�@�@�@�@��	�@�@�@�@�@��	�@�@�@�~
Mac OS X 10.5 (Leopard)	�@�@�@�@��	�@�@�@�@�@��	�@�@�@��
Mac OS X 10.6 (Snow Leopard)�@ ��	�@�@ ��	�@�@�@��
���AJAVA�̃f�t�H���g�t�@�C���G���R�[�f�B���O��J2SE5��UTF-8 , Java SE 6��SJIS
����ɁAJava#String�̓����R�[�h��Unicode(UTF-16)

�ȉ��ɏڂ�������������B
http://labs.unoh.net/2007/09/unicode-on-mac.html#c102438

 */
/**
 * 
 * @author ikeda
 *
 */
public class MacCharCode {
	// UTF-8-MAC �ɕϊ�����B
	// mac�̃t�@�C���V�X�e����UTF-8��NFD(���_�A�����_��񕶎��ŕ\���j�ƂȂ��Ă���BMAC�ȊO��UTF-8��NFC�ƂȂ��Ă���B
	//   iconv���O���v���O�����Ƃ��ė��p����shift-jis�������UTC-8-MAC�ɕϊ�����
	//   byte[]�ɕԂ����A����String�ɑ���ƁA�ꕔ�̕����ŕ�����������������B��j���R�[�_�[ �Ō�̒������Ȃ���������������
	public static byte[] String2Utf8Mac(String istr){
		byte[] ret = null;
		try {
			File tf = File.createTempFile("_wcglnch", "temp");// ��͂Ƃ���temp�t�@�C�����g�p����Bstdin���g����@�����ǂ��B
			//File tf = new File("_wcglnch.log");
			FileOutputStream os = new FileOutputStream(tf);
			byte[] sjis = istr.getBytes("Shift-JIS");
			os.write(sjis);
			os.close();
			String nm=new String(tf.getAbsolutePath());
			String cmd = new String("iconv -f shift-jis -t utf-8-mac " + nm);
			Process p = Runtime.getRuntime().exec(cmd);
			InputStream sin = p.getInputStream();
			BufferedInputStream bs = new BufferedInputStream(sin);
			p.waitFor();
			byte[] buf = new byte[4096];
			int num = bs.read(buf); 
			ret = new byte[num];
			System.arraycopy(buf, 0, ret, 0, ret.length);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return ret;
	}
	// Java Normalizer���g���o�[�W����
	public static byte[] String2Utf8Mac_2(String istr){
		// mac�̃R�}���h���C����UTF-8-mac (NFD)�Ŏw�肵�Ȃ��Ƃ����Ȃ�
		byte[] ret=null;
		try {
			if(!Normalizer.isNormalized(istr, Normalizer.Form.NFD)){
				istr = new String(Normalizer.normalize(istr, Normalizer.Form.NFD));
			}
			return istr.getBytes("UTF-8");	// SJIS��UTF-8�ɕϊ�
			
		} catch (UnsupportedEncodingException e) {
		}
		return ret;
	}
}
